#!/bin/bash
#
# Alex Alexander (wired) <alex.alexander@gmail.com>
# http://www.linuxized.com
#  Carbon Jiao 基于Alex的脚本再修改定制 for archlive-pkg
# 该脚本将内存tmpfs里面的.mozilla个人配置文件夹跟硬盘里面的文件夹同步，加快
# Firefox的运行速度，并可以确保关机也不丢失这些配置文件。
# this script makes sure your .mozilla folder is in tmpfs and constantly syncs it
# with a folder on your hdd so you won't lose anything :)
# for more details on how it works visit my blog in the link above.
#
# for this to have any meaning, the MOZTMPFS folder must be on tmpfs
# i.e. to make /var/tmp a tmpfs folder, add the following in /etc/fstab
# 预正常使用该脚本，需要将如下行去掉#放在/etc/fstab，然后mount /var/tmp
# tmpfs      		/var/tmp	tmpfs  size=768M,mode=0777         0 0
#
# don't forget to mount the first time!
# 用Archlive的就不用做上面一步了！——Archlive已经自动做好！
_ffver=3.5
# your ram mozilla folder
MOZTMPFS=/var/tmp/`whoami`_mozilla
# your original mozilla folder - i recommend: mv ~/.mozilla ~/.mozilla-hdd
MOZHDD="${HOME}/.mozilla-hdd"
# your ~/.mozilla
MOZHOME="${HOME}/.mozilla"
# seconds interval for rsync
INTERVAL=30

#sudo killall firefox
sudo killall firefox-bin
sudo killall run-mozilla.sh

init_firefox ()
{
	[ -e $MOZHDD ] && rm -rf $MOZHDD
	mkdir -p $MOZHDD/firefox/firefox.default
	echo "[General]" >$MOZHDD/firefox/profiles.ini
	echo "StartWithLastProfile=1" >>$MOZHDD/firefox/profiles.ini
	echo "" >>$MOZHDD/firefox/profiles.ini
	echo "[Profile0]" >>$MOZHDD/firefox/profiles.ini
	echo "Name=default" >>$MOZHDD/firefox/profiles.ini
	echo "IsRelative=1" >>$MOZHDD/firefox/profiles.ini
	echo "Path=firefox.default" >>$MOZHDD/firefox/profiles.ini
	cp -f /usr/lib/firefox-$_ffver/prefs.js $MOZHDD/firefox/firefox.default/
}

if [ -e ${MOZHOME} ]; then
	[ -L ${MOZHOME} ] && rm -f ${MOZHOME}
	[ ! -e ${MOZHDD} ] && mv -f ${MOZHOME} ${MOZHDD}
fi
if [ ! -d ${MOZHDD} ]; then
	init_firefox
else
	[ ! -f ${MOZHDD}/firefox/profiles.ini ] && init_firefox		
fi

# check for and create tmp folder
if [ ! -d "${MOZTMPFS}" ]; then
	mkdir -p ${MOZTMPFS}
fi

# check for ~/.mozilla
# if it exists and is a directory die
if [ -e "${MOZHOME}" ] && [ ! -L "${MOZHOME}" ]; then
	rm -rf ${MOZHOME}
else
	if [ ! -e "${MOZHOME}" ]; then
		ln -s "${MOZTMPFS}" "${MOZHOME}"
	fi
fi

# sync to tmpfs
echo "正在同步 ${MOZHDD} 到 ${MOZTMPFS}"
rsync -avi --delete "${MOZHDD}/" "${MOZTMPFS}/"

echo "每隔${INTERVAL}秒同步firefox个人配置缓存"
( while true; do sleep ${INTERVAL}; rsync -avi --delete "${MOZTMPFS}/" "${MOZHDD}/"; done; ) &
SYNC=$!

echo "正在载入Firefox";
/usr/lib/firefox-$_ffver/firefox $1

echo "Firefox已经关闭, 关闭自动同步程序，并保存firefox个人配置"
echo "请稍候..."
#if [ -e "${MOZTMPFS}/firefox/firefox.default" ]; then
#	rm -rf ${MOZTMPFS}/firefox/firefox.default/{Cache,OfflineCache}
#	rm -f ${MOZTMPFS}/firefox/firefox.default/{XUL.mfasl,XPC.mfasl,urlclassifier3.sqlite}
#fi
kill $!
rsync -avi --delete "${MOZTMPFS}/" "${MOZHDD}/"
echo "已经完成, 基于安全性考虑移除 ${MOZHOME} 链接";
rm ${MOZHOME}
sudo killall firefox-bin
sudo killall run-mozilla.sh
sudo killall firefox